package com.dongzili.easyes.custom.controller;

import com.dongzili.easyes.common.es.EsUtils;
import com.dongzili.easyes.common.mybatisplus.PropertyDbTypeEnum;
import com.dongzili.easyes.common.mybatisplus.PropertyLambdaWrapper;
import com.dongzili.easyes.common.mybatisplus.PropertyQueryWrapper;
import com.dongzili.easyes.common.utils.QueryWrapperSqlHelper;
import com.dongzili.easyes.common.vo.R;
import com.dongzili.easyes.custom.entity.SRelationModel;
import com.dongzili.easyes.custom.entity.vo.RelationVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
public class TestController {


    @GetMapping("/getSql")
    public R<?> getSql() {


        PropertyQueryWrapper<SRelationModel> wrapper = new PropertyQueryWrapper<>();
        wrapper.lambda().eq(SRelationModel::getFlag, 0);
        wrapper.lambda().gt(SRelationModel::getTermID, 0);
        wrapper.lambda().groupBy(SRelationModel::getTermID, SRelationModel::getTermName,SRelationModel::getLibraryID, SRelationModel::getLibraryName);
        wrapper.select( "termID","termName","libraryID","libraryName", "count(distinct resCode) as count");

        List<Map<String, Object>> resList = EsUtils.selectListMap(wrapper, SRelationModel.class);
        List<Map<String, String>> list = transform(resList, "termName", "libraryName", "count");
        return R.success(list);
    }

    @GetMapping("/getList")
    public R<?> getList() {

        PropertyQueryWrapper<SRelationModel> wrapper = new PropertyQueryWrapper<>(PropertyDbTypeEnum.ES);
        PropertyLambdaWrapper<SRelationModel> lambdaWrapper = wrapper.lambda();
        lambdaWrapper.eq(SRelationModel::getFlag, 0);
        lambdaWrapper.gt(SRelationModel::getTermID, 0);
        lambdaWrapper.in(SRelationModel::getOrgID, Arrays.asList(91,767));
        lambdaWrapper.groupBy(SRelationModel::getTermID, SRelationModel::getTermName,SRelationModel::getLibraryID, SRelationModel::getLibraryName);
//        lambdaWrapper.select("count(distinct resCode) as count",SRelationModel::getTermID, SRelationModel::getTermName,SRelationModel::getLibraryID, SRelationModel::getLibraryName);
        lambdaWrapper.select(Arrays.asList(SRelationModel::getTermID, SRelationModel::getTermName,SRelationModel::getLibraryID, SRelationModel::getLibraryName),"count(distinct resCode) as count");

        //        wrapper.select( "termID","termName","libraryID","libraryName", "count(distinct resCode) as count");

        System.out.println("wrapper.getSqlSelect(): "+wrapper.getSqlSelect());
        System.out.println("wrapper.getSqlComment(): "+wrapper.getSqlComment());
        System.out.println("wrapper.getSqlFirst(): "+wrapper.getSqlFirst());
        System.out.println("wrapper.getSqlSet(): "+wrapper.getSqlSet());
        System.out.println("wrapper.getSqlSegment(): "+wrapper.getSqlSegment());
        System.out.println("wrapper.getTargetSql(): "+wrapper.getTargetSql());
        System.out.println("wrapper.getCustomSqlSegment(): "+wrapper.getCustomSqlSegment());


        System.out.println("getSql: "+QueryWrapperSqlHelper.getSql(wrapper, SRelationModel.class));
        System.out.println("wrapper.toString(): "+wrapper.toString()); // 输出完整的 SQL
//        System.out.println(SqlUtils.);


        List<RelationVo> resList = EsUtils.selectList(wrapper, SRelationModel.class, RelationVo.class);
//        List<Map<String, String>> list = transform(resList, "termName", "libraryName", "count");
        return R.success(resList);
    }



    /**
     * 将原始数据列表转换为按维度分组的目标格式
     *
     * @param sourceList 原始数据列表，每个元素包含libraryName、count、termName等字段
     * @param dimensionField 维度字段名(如"termName")
     * @param nameField 名称字段名(如"libraryName")
     * @param valueField 值字段名(如"count")
     * @return 转换后的列表，按维度分组，每个维度包含各名称对应的值
     */
    public static List<Map<String, String>> transform(List<Map<String, Object>> sourceList,
                                                      String dimensionField,
                                                      String nameField,
                                                      String valueField) {
        // 参数校验
        if (sourceList == null || sourceList.isEmpty()) {
            return new ArrayList<>();
        }
        if (dimensionField == null || dimensionField.isEmpty()) {
            throw new IllegalArgumentException("维度字段名不能为空");
        }
        if (nameField == null || nameField.isEmpty()) {
            throw new IllegalArgumentException("名称字段名不能为空");
        }
        if (valueField == null || valueField.isEmpty()) {
            throw new IllegalArgumentException("值字段名不能为空");
        }

        // 按维度分组
        Map<Object, List<Map<String, Object>>> groupedByDimension = sourceList.stream()
                .collect(Collectors.groupingBy(item -> item.get(dimensionField)));

        // 转换每组数据
        List<Map<String, String>> result = new ArrayList<>();
        for (Map.Entry<Object, List<Map<String, Object>>> entry : groupedByDimension.entrySet()) {
            Map<String, String> dimensionMap = new LinkedHashMap<>();

            // 设置维度值
            String dimensionValue = entry.getKey() != null ? entry.getKey().toString() : "";
            dimensionMap.put("dimension", dimensionValue);

            // 处理每个分组内的条目
            for (Map<String, Object> item : entry.getValue()) {
                Object nameObj = item.get(nameField);
                Object valueObj = item.get(valueField);

                if (nameObj != null && valueObj != null) {
                    String name = nameObj.toString();
                    String value = valueObj.toString();
                    dimensionMap.put(name, value);
                }
            }

            result.add(dimensionMap);
        }

        // 按维度排序(可选)
        result.sort(Comparator.comparing(map -> map.get("dimension")));

        return result;
    }

}
